//
//  CPCustomerServicesViewController.m
//
//
//  Created by 崔志伟 on 2018/8/16.
//  Copyright © 2018年 崔志伟. All rights reserved.
//

#import "ChatRoomViewController.h"
#import "FriendDetailViewController.h"

#import "CPCustomerServicesRightTableViewCell.h"
#import "CPCustomerServicesLeftTableViewCell.h"
#import "WebSocketRocketManger.h"
#import "ShowContentModel.h"

@interface ChatRoomViewController ()<UITextViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    dispatch_source_t _timer ;
}
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewBgViewHight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewBgViewBottomS;
/**键盘高度*/
@property (nonatomic, assign) CGFloat keyboardHeight;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *safetyZoneBgView;
@property (nonatomic,strong) NSMutableArray  * dataArray ;
@property(nonatomic,copy)NSString * tempSendMsg ;
@property (nonatomic,strong) NSString  * customerServicesId ;

@property (nonatomic,assign) BOOL  isShowMoreInputType ;

@end

@implementation ChatRoomViewController
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
// 添加通知
-(void)addNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //链接WebSocket
    [self setUpWebSocketRocketManger];
    [self addNotification];
    self.navigationItem.title = @"聊天室";
    self.textView.layer.cornerRadius = 5;
    self.textView.layer.masksToBounds = YES;
    self.textView.layer.borderColor = UIColorFromRGB(0xf5f5f5).CGColor;
    self.textView.layer.borderWidth = 1;
    self.textViewBgViewBottomS.constant = -110-SAFEARWA_BOTTOM_HEIGHT;
    UIButton *moreBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    [moreBtn setImage:[UIImage imageNamed:@"more_info"] forState:UIControlStateNormal];
    [moreBtn addTarget:self action:@selector(moreBtnAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *btnItem = [[UIBarButtonItem alloc]initWithCustomView:moreBtn];
    self.navigationItem.rightBarButtonItem  =btnItem;    
    [self.tableView registerNib:[UINib nibWithNibName:@"CPCustomerServicesRightTableViewCell" bundle:nil] forCellReuseIdentifier:@"CPCustomerServicesRightTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"CPCustomerServicesLeftTableViewCell" bundle:nil] forCellReuseIdentifier:@"CPCustomerServicesLeftTableViewCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight = 20;
    self.dataArray =[NSMutableArray array];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

#pragma mark == UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.dataArray.count;
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
  ShowContentModel *model =   self.dataArray[indexPath.row];
    if (model.isSelfSend) {
        CPCustomerServicesRightTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CPCustomerServicesRightTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.contentLabel.text = model.chatMsg.msg;
        return cell;
    }else{
        CPCustomerServicesLeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CPCustomerServicesLeftTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.contentLabel.text = model.chatMsg.msg;
        return cell;
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
        [self.view endEditing:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewAutomaticDimension;
}

#pragma mark keyboardnotification
- (void)keyboardWillShow:(NSNotification *)notification {
    self.isShowMoreInputType = NO;
    self.safetyZoneBgView.hidden = YES;
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    _keyboardHeight = keyboardFrame.size.height;
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.textViewBgViewBottomS.constant = self->_keyboardHeight-SAFEARWA_BOTTOM_HEIGHT-110;
        [self.view layoutIfNeeded];
    }completion:^(BOOL finished) {
        [self scrollTableToFoot:YES];
    }];

}
- (void)keyboardWillHidden:(NSNotification *)notification {
    if (!self.isShowMoreInputType) {
        self.safetyZoneBgView.hidden = NO;
        CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        [UIView animateWithDuration:duration animations:^{
            self.textViewBgViewBottomS.constant = -110-SAFEARWA_BOTTOM_HEIGHT;
            [self scrollTableToFoot:YES];
            [self.view layoutIfNeeded];
        }];
    }
 
}

#pragma mark UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    [self setTextViewHight];
}
- (void)setTextViewHight{
    CGFloat contentSizeH = self.textView.contentSize.height;
    CGFloat lineH = self.textView.font.lineHeight;
    CGFloat maxTextViewHeight = ceil(lineH * 4 + self.textView.textContainerInset.top + self.textView.textContainerInset.bottom);
    if (contentSizeH <= maxTextViewHeight) {
        self.textViewBgViewHight.constant = contentSizeH+16;
    }else{
        self.textViewBgViewHight.constant = maxTextViewHeight+16;
    }
    [self.textView scrollRangeToVisible:NSMakeRange(self.textView.selectedRange.location, 1)];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{
    if ([text isEqualToString:@"\n"])
    {
        [self sendButtonClick];
        return NO;
    }
    return YES;
    
}

#pragma mark == 创建WebSocketRocketManger

- (void) setUpWebSocketRocketManger{
    //链接成功
    [WebSocketRocketManger instance].webSocketDidOpen = ^{
        
    };
    //收到服务端发送过来的消息
    [WebSocketRocketManger instance].didReceiveMessage = ^(id  _Nonnull message) {
        ShowContentModel *conteModel =  [ShowContentModel mj_objectWithKeyValues:message];
        conteModel.isSelfSend = NO;
        [self.dataArray addObject:conteModel];
        [self.tableView reloadData];
        [self scrollTableToFoot:YES];
    };
    
    [WebSocketRocketManger instance].closeWebSocketBlocl = ^{
        NSLog(@"断开客服链接");

    };
}

- (void)scrollTableToFoot:(BOOL)animated
{
    NSInteger s = [self.tableView numberOfSections];  //有多少组
    if (s<1) return;  //无数据时不执行 要不会crash
    NSInteger r = [self.tableView numberOfRowsInSection:s-1]; //最后一组有多少行
    if (r<1) return;
    NSIndexPath *ip = [NSIndexPath indexPathForRow:r-1 inSection:s-1];  //取最后一行数据
    [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:animated]; //滚动到最后一行
}

// 发送按钮
-(void)sendButtonClick {
    
    if (self.textView.text.length > 0) {
        self.tempSendMsg = self.textView.text;
        ShowContentModel *contentModel = [ShowContentModel new];
        contentModel.action = 2;
        ContentChatModel *chatMOdel =  [ContentChatModel new];
        chatMOdel.senderId = [APPUserDataManager shareInstance].userId;
        chatMOdel.receiveId = self.receiveId;
        chatMOdel.msg =self.tempSendMsg;
        contentModel.chatMsg =chatMOdel;
        contentModel.isSelfSend =YES;
        [self.dataArray addObject:contentModel];
        [self sendData:contentModel];
        self.textView.text= @"";
        [self setTextViewHight];
        [self.tableView reloadData];
        [self scrollTableToFoot:YES];
    }
  
}

- (void)sendData:(SenderContentModel *)contentModel{
    
    SenderContentModel*senderData = [SenderContentModel new];
    senderData.action =contentModel.action;
    senderData.chatMsg =contentModel.chatMsg;
    NSLog(@"=========%@",senderData.mj_JSONString);
    [[WebSocketRocketManger instance] sendMessage:senderData.mj_JSONString];
}

- (IBAction)selectMoreInputTypeAction:(id)sender {
    self.isShowMoreInputType = YES;
    self.safetyZoneBgView.hidden = YES;
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.25 animations:^{
        self.textViewBgViewBottomS.constant = 0;
        [self.view layoutIfNeeded];
    }completion:^(BOOL finished) {
        [self scrollTableToFoot:YES];
    }];
}

- (void)moreBtnAction{
    FriendDetailViewController *friendDetailVC = [FriendDetailViewController new];
    friendDetailVC.friendId =  self.receiveId;
    [self.navigationController pushViewController:friendDetailVC animated:YES];
}
@end
